package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.*;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.BeanCopyUtils;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SpuSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 封装检索分类id
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        // 封装检索品牌id
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        // 封装检索商品状态
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }

        // 封装检索关键字
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(w -> w
                    .like("spu_name", key)
                    .or()
                    .eq("id", key));
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     *
     * @param spuSaveVo spu信息保存Vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = BeanCopyUtils.copy(spuSaveVo, SpuInfoEntity.class);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);

        // 2.保存spu的描述图片 pms_spu_info_desc
        List<String> saveVoDecript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", saveVoDecript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3.保存spu的图片集 pms_spu_images
        List<String> spuImages = spuSaveVo.getImages();
        if (CollectionUtils.isEmpty(spuImages)) {
            spuImages = Collections.emptyList();
        }
        List<SpuImagesEntity> spuImagesEntityList = spuImages.stream()
                .map(image -> {
                    SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                    spuImagesEntity.setSpuId(spuInfoEntity.getId());
                    spuImagesEntity.setImgUrl(image);
                    return spuImagesEntity;
                })
                .collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntityList);

        // 4.保存spu的积分信息 gulimall_sms.sms_spu_bounds
        SpuBoundTo spuBoundTo = BeanCopyUtils.copy(spuSaveVo.getBounds(), SpuBoundTo.class);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程调用Coupon服务保存spu的积分信息失败");
        }

        // 5.保存spu的规格参数 pms_product_attr_value
        List<SpuSaveVo.BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if (CollectionUtils.isEmpty(baseAttrs)) {
            baseAttrs = Collections.emptyList();
        }
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream()
                .map(baseAttr -> {
                    ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                    productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                    productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                    productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                    productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                    AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
                    productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                    return productAttrValueEntity;
                })
                .collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        // 6.保存spu对应的所有sku信息
        List<SpuSaveVo.Skus> skuList = spuSaveVo.getSkus();
        if (CollectionUtils.isEmpty(skuList)) {
            skuList = Collections.emptyList();
        }
        skuList.forEach(sku -> {
            // 6.1保存sku基本信息 pms_sku_info
            List<SpuSaveVo.Skus.Images> imageList = sku.getImages();
            if (CollectionUtils.isEmpty(imageList)) {
                imageList = Collections.emptyList();
            }
            SkuInfoEntity skuInfoEntity = BeanCopyUtils.copy(sku, SkuInfoEntity.class);
            skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            imageList.forEach(img -> {
                if (img.getDefaultImg() == 1) {
                    skuInfoEntity.setSkuDefaultImg(img.getImgUrl());
                }
            });
            skuInfoService.save(skuInfoEntity);

            // 6.2保存sku图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesEntityList = imageList.stream()
                    // 过滤未选中图集的图片
                    .filter(item -> StringUtils.isNotBlank(item.getImgUrl()))
                    .map(image -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgUrl(image.getImgUrl());
                        skuImagesEntity.setDefaultImg(image.getDefaultImg());
                        return skuImagesEntity;
                    })
                    .collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntityList);

            // 6.3保存sku销售属性信息 pms_sku_sale_attr_value
            List<SpuSaveVo.Skus.Attr> attrList = sku.getAttr();
            if (CollectionUtils.isEmpty(attrList)) {
                attrList = Collections.emptyList();
            }
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream()
                    .map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                        skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                        skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

            // 6.4保存sku优惠信息 gulimall_sms.sms_sku_ladder
            if (sku.getFullCount() != null
                    && sku.getDiscount() != null
                    // 过滤优惠折扣为0的数据
                    && sku.getFullCount() > 0
                    && BigDecimal.ZERO.compareTo(sku.getDiscount()) < 0) {
                SkuLadderTo skuLadderTo = BeanCopyUtils.copy(sku, SkuLadderTo.class);
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                skuLadderTo.setAddOther(sku.getCountStatus());
                R r1 = couponFeignService.saveSkuLadder(skuLadderTo);
                if (r1.getCode() != 0) {
                    log.error("远程调用Coupon服务保存sku优惠信息失败");
                }
            }

            // 6.5保存sku满减信息 gulimall_sms.sms_sku_full_reduction
            SkuFullReductionTo skuFullReductionTo = BeanCopyUtils.copy(sku, SkuFullReductionTo.class);
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            R r2 = couponFeignService.saveSkuFullReduction(skuFullReductionTo);
            if (r2.getCode() != 0) {
                log.error("远程调用Coupon服务保存sku满减信息失败");
            }

            // 6.6保存sku会员价格 gulimall_sms.sms_member_price
            List<SpuSaveVo.Skus.MemberPrice> memberPriceList = sku.getMemberPrice();
            if (CollectionUtils.isEmpty(memberPriceList)) {
                memberPriceList = Collections.emptyList();
            }
            List<MemberPriceTo> memberPriceToList = memberPriceList.stream()
                    // 过滤会员价格为0的数据
                    .filter(item -> BigDecimal.ZERO.compareTo(item.getPrice()) < 0)
                    .map(memberPrice -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberLevelId(memberPrice.getId());
                        memberPriceTo.setMemberLevelName(memberPrice.getName());
                        memberPriceTo.setMemberPrice(memberPrice.getPrice());
                        memberPriceTo.setAddOther(1);
                        return memberPriceTo;
                    })
                    .collect(Collectors.toList());
            R r3 = couponFeignService.saveBatchMemberPrice(memberPriceToList);
            if (r3.getCode() != 0) {
                log.error("远程调用Coupon服务保存sku会员价格失败");
            }

        });

    }

    /**
     * 商品上架
     *
     * @param spuId 商品id
     */
    @Transactional
    @Override
    public void up(Long spuId) {
        // 需要上架的sku
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.queryBySpuId(spuId);

        // 查询sku的所有可被检索的规格属性
        List<Long> searchAttrIds = attrService.querySearchAttrsBySpuId(spuId);
        List<ProductAttrValueEntity> valueEntityList = productAttrValueService.queryByAttrIds(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = BeanCopyUtils.copyList(valueEntityList, SkuEsModel.Attrs.class);

        // 查询是否有库存
        List<Long> skuIdList = skuInfoEntityList.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        Map<Long, Boolean> skuMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            List<SkuHasStockTo> data = skuHasStock.getData(new TypeReference<List<SkuHasStockTo>>() {
            });
            skuMap = data.stream()
                    .collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务调用查询sku是否有库存失败,原因:{}", e);
        }

        // 封装skuEsModel数据
        Map<Long, Boolean> finalSkuMap = skuMap;
        List<SkuEsModel> upProducts = skuInfoEntityList.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = BeanCopyUtils.copy(skuInfoEntity, SkuEsModel.class);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // 多次查询库存系统是否有库存
            /*
            Long stock = 0L;
            R r = wareFeignService.queryWareSkuBySkuId(skuEsModel.getSkuId());
            if (r.getCode() == 0) {
                stock = (Long) r.get("data");
            }
            skuEsModel.setHasStock(stock > 0);
             */
            // 单次批量查询库存系统是否有库存
            if (finalSkuMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalSkuMap.get(skuInfoEntity.getSkuId()));
            }
            skuEsModel.setHotScore(0L);
            // 查询品牌和分类信息
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        // 调用es服务，进行保存
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 调用成功
            SpuInfoEntity infoEntity = new SpuInfoEntity();
            infoEntity.setId(spuId);
            infoEntity.setUpdateTime(new Date());
            infoEntity.setPublishStatus(ProductConstant.PublishStatusEnum.SPU_UP.getCode());
            baseMapper.updateById(infoEntity);
        } else {
            // 调用失败
        }

    }

    /**
     * 通过skuId查询spu信息
     *
     * @param skuId skuId
     * @return spu信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        return baseMapper.selectById(spuId);
    }

}